package cn.com.hhrcw.job;

import cn.com.hhrcw.entity.SysLog;
import cn.com.hhrcw.logs.entity.Logs;
import cn.com.hhrcw.logs.service.ILogsService;
import cn.com.hhrcw.service.ISysLogService;
import cn.com.hhrcw.utils.RedisLockUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统一日志上传
 *
 * @author 李星星
 * @date 2020年12月22日14:37:21
 */
@Component("LogsTask")
@Slf4j
public class LogsTask implements Job {
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.profiles.active}")
    private String active;

    @Autowired
    private ILogsService logsService;

    @Autowired
    private ISysLogService sysLogService;

    @Override
    public void execute(JobExecutionContext context) {
        //防重复执行
        String locked = "LogsTask_locked";
        String task = "LogsTask";
        if (redisTemplate.hasKey(locked)) {
            log.warn("任务执行中...");
            return;
        }
        int  a = 120;
        if (RedisLockUtils.tryLock(task, a)) {
            try {
                Date date = new Date();
                date = DateUtil.offsetDay(date, -1);
                DateTime start = DateUtil.beginOfDay(date);
                DateTime end = DateUtil.endOfDay(date);
                List<SysLog> list = sysLogService.lambdaQuery().isNotNull(SysLog::getOperateType).between(SysLog::getCreateTime, start, end).orderByAsc(SysLog::getCreateTime).list();

                List<Logs> collect = list.stream().map(e -> {
                    Logs logs = new Logs();
                    logs.setSt("1");
                    logs.setCo(e.getLogContent());
                    logs.setEnv(active);
                    logs.setIp(e.getIp());
                    logs.setLatency(e.getCostTime().toString());
                    logs.setMethod(e.getRequestType());
                    logs.setOb(e.getUserid());
                    logs.setObn(e.getUsername());
                    logs.setOp(e.getUserid());
                    logs.setOpn(e.getUsername());
                    logs.setOty("function");
                    logs.setRemark("-");
                    logs.setTime(e.getCreateTime().getTime());
                    logs.setTy(e.getOperateType());
                    logs.setUrl(e.getRequestUrl());
                    logs.setUserAgent(e.getUserAgent());
                    logs.setOptype("OP");
                    return logs;
                }).collect(Collectors.toList());
                if (CollUtil.isEmpty(collect)) {
                    return;
                }
                Object object = logsService.uploadLogs(collect);
                if (!Convert.toBool(object)) {
                    log.error("{}~{}日志上传失败,请重新处理", start, end);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                RedisLockUtils.unLock("LogsTask");
            }
        }
    }
}
